package com.sample.jqgrid.controller;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cfw.util.ControllerUtil;
import com.sample.jqgrid.service.JqgridService;

@Controller
@RequestMapping("/sample-jqgrid/*")
public class JqgridController {
	private static final Logger logger = LoggerFactory.getLogger(JqgridController.class); 

	@Autowired 
	private JqgridService jqgridService; 
	
	@RequestMapping(value = "/list.json", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> list(Locale locale, Model model) {
		return jqgridService.list();
	}
	
	@RequestMapping(value = "/save.json", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> save(@RequestBody final Map<String, Object> param) {
		logger.debug("********************************************************************************");
		logger.debug("JqgridController.save");
		logger.debug("*** param:" + param);
		logger.debug("********************************************************************************");
		
		List<Map<String, Object>> data = (List<Map<String, Object>>)param.get("data");
		for (Map<String, Object> map : data) {
			if (map.containsKey("added") && (Boolean)map.get("added")) {
				// insert data
				logger.debug("insert:" + map);
			} else
			if (map.containsKey("deleted") && (Boolean)map.get("deleted")) {
				// deleted data
				logger.debug("delete:" + map);
			} else {
				// update data
				logger.debug("update:" + map);
			}
		}
		
		return ControllerUtil.getSuccessMap();
	}	
}
